using System.Collections.Generic;
using UnityEngine;
using Random = System.Random;

public class MapBehaviour : MonoBehaviour {
	public InfiniteMap Map;

	public int MapHeight = 6;

	public bool ApplyBoundaryConstraints = true;

	public Vector3 GetWorldspacePosition(Vector3Int position) {
		return this.transform.position
			+ Vector3.up * InfiniteMap.BLOCK_SIZE / 2f
			+ new Vector3(position.x, position.y, position.z) * InfiniteMap.BLOCK_SIZE;
	}

	public Vector3Int GetMapPosition(Vector3 worldSpacePosition) {
		var pos = (worldSpacePosition - this.transform.position) / InfiniteMap.BLOCK_SIZE;
		return Vector3Int.FloorToInt(pos + new Vector3(0.5f, 0, 0.5f));
	}

	public void Clear() {
		var children = new List<Transform>();
		foreach (Transform child in this.transform) {
			children.Add(child);
		}
		foreach (var child in children) {
			GameObject.DestroyImmediate(child.gameObject);
		}
		this.Map = null;
	}

	public void Initialize() {
		this.Clear();
		this.Map = new InfiniteMap(this.MapHeight);
	}

	public bool Initialized {
		get {
			return this.Map != null;
		}
	}
	
	public void Update() {
		if (this.Map == null || this.Map.BuildQueue == null) {
			return;
		}

		int itemsLeft = 50;

		while (this.Map.BuildQueue.Count != 0 && itemsLeft > 0) {
			var slot = this.Map.BuildQueue.Peek();
			if (slot == null) {
				return;
			}
			if (this.BuildSlot(slot)) {
				itemsLeft--;
			}
			this.Map.BuildQueue.Dequeue();
		}
	}

    Random rand = new Random();
	public bool BuildSlot(Slot slot) {
		if (slot.GameObject != null) {
#if UNITY_EDITOR
			GameObject.DestroyImmediate(slot.GameObject);
#else
			GameObject.Destroy(slot.GameObject);
#endif
		}

		//if (!slot.Collapsed) {
		//	return false;
		//}

		var gameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
		gameObject.name = "Cube_" + slot.Position;
		gameObject.transform.parent = this.transform;
		gameObject.transform.position = this.GetWorldspacePosition(slot.Position);
        // Get the Renderer component from the new cube
        var cubeRenderer = gameObject.GetComponent<Renderer>();

        // Call SetColor using the shader property name "_Color" and setting the color to red
        cubeRenderer.material.SetColor("_Color", new Color((float)rand.Next(0, 1000)/1000f,(float)rand.Next(0, 1000)/1000f,(float)rand.Next(0, 1000)/1000f));
		Debug.Log($"cube color : {cubeRenderer.material.color}");
        slot.GameObject = gameObject;
		return true;
	}

	public void BuildAllSlots() {
		while (this.Map.BuildQueue.Count != 0) {
			this.BuildSlot(this.Map.BuildQueue.Dequeue());
		}
	}
}
